package com.zhuss.car.processor;

import com.zhuss.bean.bo.car.driver.StopDriverBo;
import com.zhuss.bean.vo.car.driver.DetailDriverVo;
import com.zhuss.car.db.dao.ext.DriverDao;
import com.zhuss.car.db.entity.Driver;
import com.zhuss.car.processor.cache.DriverCache;
import com.zhuss.common.AbstractProcessor;
import com.zhuss.common.Processor;
import com.zhuss.db.entity.OpLog;
import com.zhuss.enums.LogActionEnum;
import com.zhuss.enums.MoudleEnum;
import com.zhuss.enums.StartStopEnum;
import com.zhuss.exception.DzcxException;
import com.zhuss.exception.ExceptionCode;
import com.zhuss.util.JsonUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * @author summer
 * @date 2020/12/23 17:07
 */
@Component("driverStop")
public class DriverStop extends AbstractProcessor<Object, StopDriverBo> implements Processor<Object, StopDriverBo> {

    @Autowired
    private DriverDao driverDao;

    @Autowired
    @Qualifier("driverRead")
    private DriverRead driverRead;

    @Autowired
    @Qualifier("driverCache")
    private DriverCache driverCache;

    @Override
    public void check(StopDriverBo param) throws DzcxException {
        //驾驶员已排班不能被删除  （根据时间，查询班次是否被占用）
        if (driverDao.trainByDriverId(param.getDriverId()) > 0) {
            throw new DzcxException(ExceptionCode.该驾驶员已被排班次);
        }

        DetailDriverVo carVo = (DetailDriverVo) driverRead.detail(param.getDriverId());
        if (StartStopEnum.停用.sameKey(carVo.getStatus())) {
            throw new DzcxException(ExceptionCode.当前数据不满足停用条件);
        }
    }

    @Override
    public Object process(StopDriverBo param) throws DzcxException {
        Long driverId = param.getDriverId();

        Driver record = new Driver();
        record.setDriverId(driverId);
        record.setStatus(param.getStatus());

        record.setModifierId(param.getConcurrentUserId());
        record.setModifier(param.getConcurrentUserName());
        record.setModifyTime(new Date());
        driverDao.updateByPrimaryKeySelective(record);

        String name = ((DetailDriverVo) driverRead.detail(driverId)).getName();

        param.setName(name);

        driverCache.clear(driverId);
        return null;
    }

    @Override
    public Object log(StopDriverBo param) throws DzcxException {
        OpLog record = new OpLog();
        record.setMoudle(MoudleEnum.车辆.key());
        record.setAction(LogActionEnum.司机停用.key());
        record.setTargetId(param.getConcurrentUserId());
        record.setTargetName(param.getName());
        record.setContent("参数: " + JsonUtil.toJson(param));
        record.setReason(param.getExceptionReason());
        record.setCreatorId(param.getConcurrentUserId());
        record.setCreator(param.getConcurrentUserName());
        record.setCreateTime(new Date());
        log(record);
        return null;
    }
}
